<template>
  <view class="vote-ranking">
    <view class="title">实时投票排行榜</view>
    
    <view class="filter-container">
      <view class="category-select">
        <picker 
          :range="categoryOptions" 
          :range-key="'name'" 
          @change="onCategoryChange" 
          :value="currentCategoryIndex"
        >
          <view class="picker">
            {{ currentCategoryName }}
            <text class="arrow-icon">▼</text>
          </view>
        </picker>
      </view>
      
      <view class="search-container">
        <view class="search-box">
          <text class="search-icon">🔍</text>
          <input 
            type="text" 
            placeholder="搜索投票选项..." 
            v-model="searchKeyword"
            @input="handleSearch"
          />
        </view>
      </view>
    </view>
    
    <view class="update-time">更新时间: {{ updateTime }}</view>
    
    <view class="ranking-list">
      <view 
        class="ranking-item" 
        :class="getRankHighlightClass(item.rank)" 
        v-for="item in filteredRankingList" 
        :key="item.projectId"
      >
        <view class="rank-badge" :class="getRankBadgeClass(item.rank)">
          {{ item.rank }}
        </view>
        <view class="option-image">
          <image :src="item.image || defaultImage" mode="aspectFill"></image>
        </view>
        <view class="option-details">
          <view class="option-name">{{ item.name }}</view>
          <view class="option-desc">{{ item.description || defaultDescription }}</view>
          <view class="vote-count">票数: {{ item.totalVotes }}</view>
        </view>
        <view class="vote-button">
          <button 
            :class="{'voted': hasVoted(item.projectId)}"
            @click="toggleVote(item.projectId)"
          >
            <text class="button-text">{{ hasVoted(item.projectId) ? '已投票' : '投票' }}</text>
            <text class="button-icon">{{ hasVoted(item.projectId) ? '✓' : '+' }}</text>
          </button>
        </view>
      </view>
    </view>
    
    <view v-if="filteredRankingList.length === 0" class="no-result">
      没有找到与 "{{ searchKeyword }}" 相关的 {{ currentCategoryName }} 选项
    </view>
  </view>
</template>

<script>
import { getVoteProjectList } from "@/api/vote.js";

export default {
  data() {
    return {
      rankingList: [],
      votedOptions: [],
      updateTime: '',
      timer: null,
      defaultImage: 'https://picsum.photos/200/200?random=option',
      defaultDescription: '这是一个投票选项，点击投票支持TA！',
      searchKeyword: '',
      filteredRankingList: [],
      categories: [
        { id: 'all', name: '全部类型' },
        { id: 'tech', name: '科技类' },
        { id: 'team', name: '团队类' },
        { id: 'design', name: '设计类' },
        { id: 'social', name: '社会责任类' }
      ],
      currentCategory: 'all',
      currentCategoryIndex: 0
    }
  },
  computed: {
    currentCategoryName() {
      const category = this.categories[this.currentCategoryIndex];
      return category ? category.name : '全部类型';
    },
    categoryOptions() {
      return this.categories;
    }
  },
  methods: {
    toggleVote(optionId) {
      if (this.hasVoted(optionId)) {
        this.votedOptions = this.votedOptions.filter(id => id !== optionId);
        this.sendVote(optionId, false);
      } else {
        this.votedOptions.push(optionId);
        this.sendVote(optionId, true);
      }
    },
    
    hasVoted(optionId) {
      return this.votedOptions.includes(optionId);
    },
    
    sendVote(optionId, isVote) {
      console.log(`投票请求: 项目ID=${optionId}, 操作=${isVote ? '投票' : '取消投票'}`);
      this.updateRankingData();
    },
    
    async fetchCategories() {
      try {
        // 实际项目中应通过API获取分类数据
        // 此处暂时保留模拟数据，待分类API开发完成后替换
        const response = {
          data: [
            { id: 'all', name: '全部类型' },
            { id: 'tech', name: '科技类' },
            { id: 'team', name: '团队类' },
            { id: 'design', name: '设计类' },
            { id: 'social', name: '社会责任类' }
          ]
        };
        
        this.categories = response.data;
        this.currentCategory = 'all';
        this.currentCategoryIndex = 0;
      } catch (error) {
        console.error('获取分类数据失败:', error);
      }
    },
    
    async updateRankingData() {
      try {
        // 调用API获取投票项目列表
        const response = await getVoteProjectList({
          category: this.currentCategory // 传递当前分类用于筛选
        });
        
        // 处理API返回数据，映射到组件需要的格式
        let projects = response.data || [];
        
        // 按类型筛选（如果后端未处理）
        if (this.currentCategory !== 'all') {
          projects = projects.filter(project => project.type === this.currentCategory);
        }
        
        // 按票数降序排序并添加排名
        const sortedProjects = projects.sort((a, b) => b.totalVotes - a.totalVotes)
          .map((project, index) => ({
            ...project,
            rank: index + 1,
            id: project.projectId // 映射项目ID
          }));
        
        this.rankingList = sortedProjects;
        this.filteredRankingList = [...this.rankingList];
        this.updateTime = new Date().toLocaleTimeString();
      } catch (error) {
        console.error('获取投票数据失败:', error);
        // 可以在这里显示错误提示或使用缓存数据
      }
    },
    
    getRankHighlightClass(rank) {
      switch(rank) {
        case 1: return 'first-place';
        case 2: return 'second-place';
        case 3: return 'third-place';
        default: return 'normal-place';
      }
    },
    
    getRankBadgeClass(rank) {
      switch(rank) {
        case 1: return 'first-badge';
        case 2: return 'second-badge';
        case 3: return 'third-badge';
        default: return 'normal-badge';
      }
    },
    
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.filteredRankingList = [...this.rankingList];
        return;
      }
      
      const keyword = this.searchKeyword.trim().toLowerCase();
      this.filteredRankingList = this.rankingList.filter(item => 
        item.name.toLowerCase().includes(keyword) || 
        (item.description && item.description.toLowerCase().includes(keyword))
      );
    },
    
    onCategoryChange(e) {
      this.currentCategoryIndex = e.detail.value;
      this.currentCategory = this.categories[this.currentCategoryIndex].id;
      this.searchKeyword = ''; // 切换分类时清空搜索框
      this.updateRankingData(); // 根据新分类刷新数据
    }
  },
  mounted() {
    this.fetchCategories(); // 从API获取分类数据
    this.updateRankingData();
    
    // 启动定时器定期刷新数据
    this.timer = setInterval(() => {
      this.updateRankingData();
    }, 5000);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
}
</script>

<style>
/* 样式部分与原代码一致，此处省略 */
</style>